package com.xiaoyu.lanling.feature.conversation.viewholder

import `in`.srain.cube.util.TimeUtils
import `in`.srain.cube.util.log.LogEvent
import `in`.srain.cube.views.list.ViewHolderBase
import android.content.Context
import android.content.DialogInterface
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.emoji.widget.EmojiTextView
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.entity.ConversationEntity
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.im.provider.ConversationManager
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.feature.conversation.model.MainConversationItem
import com.xiaoyu.lanling.log.AppLogClient
import com.xiaoyu.lanling.media.image.ImageViewUtil
import com.xiaoyu.lanling.router.Router
import com.xiaoyu.lanling.util.TextViewUtil
import com.xiaoyu.lanling.view.UserAvatarDraweeView
import com.xiaoyu.lanling.view.text.UserNameTextView

class MainConversationViewHolder : ViewHolderBase<MainConversationItem>() {

    companion object {
        val sOnItemClickListener: (View) -> Unit = { view ->
            val itemData = view.getViewTag<MainConversationItem>()
            itemData?.let {
                Router.instance.gotoChatActivity("", itemData.entity.chatId, "")
            }
        }

        private val sViewLongClickListener = OnLongClickListener { v: View ->
            val itemData = v.getViewTag<MainConversationItem>() ?: return@OnLongClickListener false
            val isTop = itemData.isTop
            val topActionRes = if (isTop) R.string.main_conversation_action_remove_from_top else R.string.main_conversation_action_stick_on_top
            val items = arrayOf<CharSequence>(AppContext.getString(topActionRes), AppContext.getString(R.string.main_conversation_action_delete_conversation), AppContext.getString(R.string.main_conversation_action_delete_all_conversation))
            val builder = AlertDialog.Builder(v.context)
            builder.setItems(items) { _: DialogInterface?, which: Int ->
                when (which) {
                    0 -> ConversationManager.getInstance().updateTopWeightAsync(itemData.entity.chatId, if (isTop) 0 else System.currentTimeMillis())
                    1 -> {
                        ConversationManager.getInstance().deleteConversationAsync(itemData.entity.chatId)
                        logEventForDeleteSingleConversation(itemData.entity)
                    }
                    2 -> {
                        showDeleteAllConversationDialog(v.context)
                    }
                }
            }
            builder.show()
            true
        }

        private fun showDeleteAllConversationDialog(context: Context) {
            AlertDialog.Builder(context)
                    .setMessage(R.string.main_conversation_action_delete_all_conversation_dialog_message)
                    .setNegativeButton(R.string.action_cancel) { _, _ -> }
                    .setPositiveButton(R.string.action_confirm) { _, _ ->
                        ConversationManager.getInstance().deleteAllConversationAsync()
                        logEventForDeleteAllConversation()
                    }
                    .show()
        }

        private fun logEventForDeleteSingleConversation(entity: ConversationEntity) {
            val logEvent = LogEvent("deleteConversation")
            logEvent.putData("action", "singleDelete")
            logEvent.putData("chatId", entity.chatId)
            logEvent.putData("toUid", entity.toUid)
            logEvent.putData("conversationType", entity.type)
            logEvent.putData("status", entity.status)
            logEvent.putData("conversationName", entity.name)
            AppLogClient.instance.addLog(logEvent)
        }

        private fun logEventForDeleteAllConversation() {
            val logEvent = LogEvent("deleteConversation")
            logEvent.putData("action", "allDelete")
            AppLogClient.instance.addLog(logEvent)
        }
    }

    private lateinit var mIcon: UserAvatarDraweeView
    private lateinit var mName: UserNameTextView
    private lateinit var mOfficialIcon: TextView
    private lateinit var mUnreadCount: TextView
    private lateinit var mDesc: EmojiTextView
    private lateinit var mTime: TextView

    override fun createView(layoutInflater: LayoutInflater, parent: ViewGroup): View? {
        val view = layoutInflater.inflate(R.layout.item_main_conversation, parent, false)
        mIcon = view.findViewById(R.id.icon)
        mName = view.findViewById(R.id.name)
        mOfficialIcon = view.findViewById(R.id.official_icon)
        mUnreadCount = view.findViewById(R.id.unread_count)
        mDesc = view.findViewById(R.id.desc)
        mTime = view.findViewById(R.id.time)

        view.setOnClickDebounceListener(sOnItemClickListener)
        view.setOnLongClickListener(sViewLongClickListener)

        return view
    }

    override fun showData(position: Int, itemData: MainConversationItem) {
        ImageViewUtil.loadImage(mIcon, itemData.iconLoadParams)
        mName.setUser(itemData.user)
        if (!itemData.isSingleChat) {
            mName.text = itemData.entity.name
        }
        mOfficialIcon.visibility = if (UserData.getInstance().isSystemAccount(itemData.user)) View.VISIBLE else View.GONE
        mDesc.text = itemData.lastContentWrapper.desc
        mDesc.setTextColor(if (itemData.lastContentWrapper.textColor == -1) AppContext.getColor(R.color.colorSecondaryText) else itemData.lastContentWrapper.textColor)

        mTime.text = if (TextUtils.isEmpty(itemData.lastContentWrapper.desc)) "" else TimeUtils.getSimpleTime(itemData.entity.lastUpdateTime)
        mCurrentView.setBackgroundColor(AppContext.getColor(if (itemData.isTop) R.color.colorBackgroundDark else R.color.colorBackground))
        mCurrentView.setViewTag(itemData)
        TextViewUtil.displayFor99PlusType(mUnreadCount, itemData.newTipCount)
    }
}